import logging
import sys
import os
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import Optional

from .config import ensure_data_dirs, get_settings, get_project_root


_LOGGER_INITIALIZED = False


def get_logger(name: Optional[str] = None) -> logging.Logger:
    global _LOGGER_INITIALIZED

    logger = logging.getLogger(name if name else "quantitative")
    if _LOGGER_INITIALIZED:
        return logger

    dirs = ensure_data_dirs()
    settings = get_settings()

    level = getattr(logging, settings["system"].get("log_level", "INFO").upper(), logging.INFO)

    logger.setLevel(level)
    logger.propagate = False

    fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")

    # Console handler with UTF-8 encoding support for Windows
    try:
        # Try to set console output encoding to UTF-8
        if sys.platform == "win32":
            # For Windows, try to set the console to UTF-8
            if hasattr(sys.stdout, 'reconfigure'):
                sys.stdout.reconfigure(encoding='utf-8', errors='replace')
            else:
                # Fallback for older Python versions
                import codecs
                sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach(), errors='replace')
                sys.stderr = codecs.getwriter('utf-8')(sys.stderr.detach(), errors='replace')

        ch = logging.StreamHandler()
        ch.setLevel(level)
        ch.setFormatter(fmt)
        logger.addHandler(ch)
    except Exception as e:
        # If UTF-8 setup fails, use default encoding
        ch = logging.StreamHandler()
        ch.setLevel(level)
        ch.setFormatter(fmt)
        logger.addHandler(ch)

    # File handler (rotating)
    log_file = dirs["log_dir"] / "app.log"
    fh = RotatingFileHandler(log_file, maxBytes=2 * 1024 * 1024, backupCount=5, encoding="utf-8")
    fh.setLevel(level)
    fh.setFormatter(fmt)
    logger.addHandler(fh)

    _LOGGER_INITIALIZED = True
    return logger